/*
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.common.shiro.bean.UserModel;

/**
 * 管理在线用户
 * 
 * @author limk
 * @date 2018年2月11日 下午4:50:30
 * @version 1.0
 */
public class ClientManager {
	
	private static final Logger LOGGER = LogManager.getLogger(ClientManager.class);

	private static ClientManager instance = new ClientManager();

	private ClientManager() {

	}

	public static ClientManager getInstance() {
		return instance;
	}

	private Map<String, UserModel> map = new HashMap<String, UserModel>();

	/**
	 * 把在线用户缓存和sessionId绑定
	 * 
	 * @param sessionId
	 * @param client
	 */
	public void addClinet(String sessionId, UserModel client) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("将用户{" + client.getUserName() + "}与session{" + sessionId + "}绑定");
		}
		map.put(sessionId, client);
	}

	/**
	 * 把在线用户缓存和sessionId绑定
	 * 
	 * @param sessionId
	 * @param client
	 */
	public void addClinet(String sessionId, String username) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("将用户{" + username + "}与session{" + sessionId + "}绑定");
		}
		map.put(sessionId, getUserModel(username));
	}

	/**
	 * 通过sessionId获取用户缓存对象
	 * 
	 * @param sessionId
	 * @return
	 */
	public UserModel getClient(String sessionId) {
		return map.get(sessionId);
	}

	/**
	 * 获取所有的在线用户信息
	 * 
	 * @return
	 */
	public Collection<UserModel> getAllClient() {
		return map.values();
	}

	/**
	 * 通过用户名获取用户缓存对象
	 * 
	 * @param username
	 * @return
	 */
	public UserModel getUserModel(String username) {
		if (username != null) {
			ArrayList<UserModel> list = new ArrayList<UserModel>(this.getAllClient());
			for (UserModel model : list) {
				if (username.equalsIgnoreCase(model.getUserName())) {
					return model;
				}
			}
		}
		return null;
	}

	/**
	 * 通过用户名获取在线用户的sessionId
	 * 
	 * @param username
	 * @return
	 */
	public String getSessionId(String username) {
		UserModel model = getUserModel(username);
		if (model != null) {
			Object o = null;
			/*
			 * 这里关键是那个entrySet()的方法,它会返回一个包含Map.Entry集的Set对象.
			 * Map.Entry对象有getValue和getKey的方法,利用这两个方法就可以达到从值取键的目的了 *
			 */
			Set<Map.Entry<String, UserModel>> set = map.entrySet();
			Iterator<Map.Entry<String, UserModel>> it = set.iterator();
			while (it.hasNext()) {
				Map.Entry<String, UserModel> entry = (Map.Entry<String, UserModel>) it.next();
				if (entry.getValue().equals(model)) {
					o = entry.getKey();
				}
			}
			return (String) o;
		}
		return null;

	}
}
